//
//  ZCAssignCodeEditVehicleViewController.m
//  ZhiChe-Wms
//
//  Created by grj on 2018/12/12.
//  Copyright © 2018 Regina. All rights reserved.
//

#import "ZCAssignCodeEditVehicleViewController.h"
#import "ZCAssignCodeVehicleTableViewCell.h"
#import "ZCAssignCodeModel.h"

@interface ZCAssignCodeEditVehicleViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) BOOL isSearch;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) ZCAssignCodeVehicleModel *vehicleModel;

@end

static NSString *vehicleCellID = @"ZCAssignCodeVehicleTableViewCell";

@implementation ZCAssignCodeEditVehicleViewController

#pragma mark - 懒加载
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, space(522), 30)];
        _searchBar.placeholder = @"请输入车型";
        _searchBar.delegate = self;
    }
    return _searchBar;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, self.view.bounds.size.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCAssignCodeVehicleTableViewCell class] forCellReuseIdentifier:vehicleCellID];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, space(522), 30)];
    [titleView addSubview:self.searchBar];
    self.navigationItem.titleView = titleView;
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [rightButton setTitle:@"取消" forState:UIControlStateNormal];
    [rightButton setTitleColor:ZCColor(0x000000, 0.87) forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] init]];
    [self.view addSubview:self.tableView];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self loadData];
}

#pragma mark - 按钮点击
- (void)backClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length > 0) {
        self.isSearch = YES;
    }else {
        self.isSearch = NO;
    }
    [self loadData];
}


#pragma mark - 网络请求
- (void)loadData {
    self.page = 1;
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    if (self.isSearch && self.searchBar.text.length > 0) {
        [params setObject:self.searchBar.text forKey:@"condition[name]"];
    }
    [params setObject:@(self.page) forKey:@"current"];
    [params setObject:@(30) forKey:@"size"];
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    [self.dataArray removeAllObjects];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:VehicleList params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.vehicleModel = [ZCAssignCodeVehicleModel yy_modelWithJSON:responseObject[@"data"]];
                [weakSelf.dataArray addObjectsFromArray:weakSelf.vehicleModel.records];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                if (weakSelf.vehicleModel.records.count < 30) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }else {
                [weakSelf.tableView.mj_header endRefreshing];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableView.mj_header endRefreshing];
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

- (void)loadMoreData {
    self.page++;
    if (self.page <= [self.vehicleModel.pages integerValue]) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        if (self.isSearch && self.searchBar.text.length > 0) {
            [params setObject:self.searchBar.text forKey:@"condition[name]"];
        }
        [params setObject:@(self.page) forKey:@"current"];
        [params setObject:@(30) forKey:@"size"];
        [self.hud showAnimated:YES];
        __weak typeof(self)weakSelf = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:VehicleList params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    [weakSelf.hud hideAnimated:YES];
                    weakSelf.vehicleModel = [ZCAssignCodeVehicleModel yy_modelWithJSON:responseObject[@"data"]];
                    [weakSelf.dataArray addObjectsFromArray:weakSelf.vehicleModel.records];
                    [weakSelf.tableView reloadData];
                    if (weakSelf.vehicleModel.records.count < 30) {
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                }else {
                    weakSelf.page--;
                    [weakSelf.tableView.mj_footer endRefreshing];
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                weakSelf.page--;
                [weakSelf.tableView.mj_footer endRefreshing];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }];
        });
    }
}


#pragma mark - UITableViewDateSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCAssignCodeVehicleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:vehicleCellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    ZCAssignCodeVehicleInfoModel *infoModel = (ZCAssignCodeVehicleInfoModel *)self.dataArray[indexPath.row];
    cell.content = infoModel.name;
    cell.showLine = YES;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(90);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self)weakSelf = self;
    ZCAssignCodeVehicleInfoModel *infoModel = (ZCAssignCodeVehicleInfoModel *)self.dataArray[indexPath.row];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"确认将车型调整为“%@”吗？",infoModel.name] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"重新选择" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
    }];
    
    UIAlertAction *commitAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:weakSelf.key forKey:@"condition[key]"];
        [params setObject:infoModel.name forKey:@"condition[modifiedVehicleType]"];
        [params setObject:infoModel.code forKey:@"condition[modifiedVehicleCode]"];
        [weakSelf.hud showAnimated:YES];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:UpdateVehicle params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    [weakSelf.hud hideAnimated:YES];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else {
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }];
        });
    }];
    
    [alertVC addAction:cancelAction];
    [alertVC addAction:commitAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

@end
